package com.wave.wavesystem.business.service.impl;

import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.wave.wavesystem.business.mapper.RoleMapper;
import com.wave.wavesystem.business.pojo.entity.RoleEntity;
import com.wave.wavesystem.business.pojo.vo.RoleVO;
import com.wave.wavesystem.business.service.RoleService;
import com.wave.wavesystem.common.util.Func;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 夕下风波
 * @date 2025-02-11
 * @description 角色表 业务层接口
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements RoleService {

    @Override
    public List<RoleVO> allRole() {
        QueryChain<RoleEntity> queryChain = QueryChain.of(RoleEntity.class).isNull(RoleEntity::getParentId);
        List<RoleEntity> parentRoles = this.list(queryChain);
        if (Func.isEmpty(parentRoles)) return Collections.emptyList();
        return fillRole(parentRoles);
    }

    /**
     * 获取全部角色
     *
     * @param parentRoles 父亲级角色
     */
    private List<RoleVO> fillRole(List<RoleEntity> parentRoles) {
        List<RoleVO> allRole = new ArrayList<>();
        for (RoleEntity parentRole : parentRoles) {
            RoleVO RoleVO = new RoleVO();
            BeanUtils.copyProperties(parentRole, RoleVO);
            allRole.add(RoleVO);
            List<RoleEntity> childrenRoles = this.list(QueryChain.of(RoleEntity.class)
                    .eq(RoleEntity::getParentId, parentRole.getId()));
            if (Func.isEmpty(childrenRoles)) continue;
            List<RoleVO> childrenRole = fillRole(childrenRoles);
            RoleVO.setChildren(childrenRole);
        }
        return allRole;
    }

    /**
     * 获取全部角色
     *
     * @param parentRoleIds 父级部门id
     */
    public List<Long> findBelongsRole(List<Long> parentRoleIds) {
        List<Long> allRole = new ArrayList<>();
        for (Long parentRoleId : parentRoleIds) {
            allRole.add(parentRoleId);
            List<RoleEntity> childrenRoles = this.list(QueryChain.of(RoleEntity.class).eq(RoleEntity::getParentId, parentRoleId));
            if (Func.isEmpty(childrenRoles)) continue;
            List<Long> ids = childrenRoles.stream().map(RoleEntity::getId).toList();
            List<Long> childrenRole = findBelongsRole(ids);
            allRole.addAll(childrenRole);
        }
        return allRole;
    }


}
